package cc.customer.common.utils;

import cc.customer.common.domain.ResponseBo;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.sound.sampled.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.Map;

/**
 * @author yhsh
 * @version 1.0
 * @since JDK 1.8.0_21
 * 类说明：  文件上传
 */
public class FileUploadUtil {
    private static final Logger logger = LoggerFactory.getLogger(FileUploadUtil.class);

    /**文件上传**/
    public static ResponseBo excuteFiles(String url,MultipartFile []file){
        if(StringUtils.isEmpty(url)||file.length<=0){
            return ResponseBo.error(" file is null or url error;url: "+url+" ;file length: "+file.length);
        }
        File fileUrl  = new File(url);
        if(!fileUrl.exists()){
            logger.info("create file ");
            fileUrl.mkdirs();
        }
        JSONArray array = new JSONArray();
        for(int i=0;i<file.length;i++){
            if(file[i]!=null){
                JSONObject obj  = executeFile(url,file[i]);
                int code = obj.getInteger("code");
                if(code==500){
                    return ResponseBo.error("execute file save is error");
                }
                String path = obj.getString("url");
                array.add(path);
            }
        }
        return ResponseBo.ok("ok", array);
    }

    /**文件上传处理**/
    public static JSONObject executeFile(String url,MultipartFile file){
        JSONObject obj=  new JSONObject();
        String SourceFileName = file.getOriginalFilename();
        Integer  lastIndex = SourceFileName.lastIndexOf(".");
        String suffix = SourceFileName.substring(lastIndex);
        String nowName  = System.currentTimeMillis()+suffix;
        String path = url+nowName;
        File serfile = new File(path);
        logger.info("文件上传的格式:"+suffix);
        try {
            file.transferTo(serfile);
        }catch (IOException e) {
            logger.error(e.getMessage());
            obj.put("code", 500);
            return obj;
        }
        logger.info("上传的路径:"+path);
        obj.put("code", 200);
        obj.put("url", path);
        return obj;
    }

    /**上传录音文件保持原有的文件名称**/
    public static ResponseBo excuteFilesKeepName(MultipartFile []file){
        File pathall = null;
        try {
            pathall = new File(ResourceUtils.getURL("classpath:").getPath());
        } catch (FileNotFoundException e) {
            logger.error("文件路径找不到："+e.getMessage());
            e.printStackTrace();
        }
        if(file.length<=0){
            return ResponseBo.error();
        }
        JSONArray array = new JSONArray();
        for(int i=0;i<file.length;i++){
            if(file[i]!=null){
                String SourceFileName = file[i].getOriginalFilename();
                String path = "static/upload/"+SourceFileName;
                File serfile  = new File(pathall.getAbsolutePath(),path);
                try {
                    file[i].transferTo(serfile);
                }catch (IOException e) {
                   return ResponseBo.error();
                }
                array.add(path);
            }
        }
        return ResponseBo.ok("ok", array);
    }

    /**获取上传录音的时长**/
    public static String getFileRecordTime(String url){
        String ids = "";
        try {
            String  record = new File(ResourceUtils.getURL("classpath:").getPath()).getAbsolutePath();
            url = record+"/static/upload/"+url;
            Long timer = VideoUtil.getDuration(url);
            ids = timer+"";
            logger.info("产生录音的时长:"+ ids+" 秒");
        }catch (Exception e){
            logger.error("获取录音时长失败: "+e.getMessage());
        }
        return ids;
    }

    public static JSONObject getRecordDruidTime(String filename) {

	    Process process = null;
	    JSONObject json = new JSONObject();
	    try {
		    String  record = new File(ResourceUtils.getURL("classpath:").getPath()).getAbsolutePath();
		    //String exce = "G:\\EnterpriseSystem\\Speexw\\speexw.exe";

		    String url = record+"/static/upload/"+filename;
            File file = new File(url);
            logger.error("解析的录音路径是："+url );
            //String[] cmd = {exce,url,url+"_backend.wav"};
            process = Runtime.getRuntime().exec("G:\\EnterpriseSystem\\Speexw\\speexw.exe "+url+" "+url+"_backend.wav");
            //new ProcessBuilder(cmd).start();
            int exitVal = process.waitFor();
            logger.error("解析的录音数据是："+exitVal );                //0
            long fileS = file.length();
            DecimalFormat df = new DecimalFormat("#.00");
            String time = df.format((double) fileS / 1024) ;
            String fileZhuan = filename+"_backend.wav";
            json.put("time",time);
            json.put("url",fileZhuan);
	    } catch (Exception e) {
	        logger.error("解析录音文件失败："+e.getMessage());
            json.put("time","0");
            json.put("url","");
	    }finally {
		    if (process != null){
			    process.destroy();
		    }
	    }
	    return json;
    }


}
